// import {composeHighlightFromViewstate, stringifyHighlighsToViewstate} from "../utils/viewstateManager.js";
// import {storeViewstate} from "../utils/storageManager.js";
// import {highlight, highlightByText} from './highlight/index.js';
import $ from "jquery";
import {composeHighlightFromViewstate, stringifyHighlighsToViewstate} from "~manager/viewstateManager";
import { store } from "~storage/store";

async function updateComments(highlightId, viewstate, comments = "") {
  console.log("inside updateComments");
  // const highlights = $(`.highlighter--highlighted[data-highlight-id='${highlightId}']`);
  //
  // highlights.css('backgroundColor', color.color); // Change the background color attribute
  // highlights.css('color', color.textColor || "inherit");
  //
  // updateStorage(highlightId, window.location.hostname + window.location.pathname, window.location.pathname, null, null, comments); // update the value in the local storage
  const url = location.hostname + location.pathname;
  const highlightWithViewstate = await updateHighlightComments(url, viewstate, comments); // update the value in the local storage
  const highlights = $(`.highlighter--highlighted[data-highlight-id='${highlightId}']`);
  for (let i=0; i<highlights.length; i++){
    highlights[i].setAttribute("viewstate", highlightWithViewstate.viewstate);
  }
  await store(url, highlightWithViewstate.viewstate);
}

async function updateHighlightComments(url, viewstate, comments) {
  const highlight = composeHighlightFromViewstate(viewstate);
  if (comments !== undefined && comments !== null) { // JM: 如果用户传入的是null或undefined，则维持原comments，要清空comments需传空字符串
    highlight.comments = comments;
  }
  highlight.viewstate = stringifyHighlighsToViewstate(highlight);

  return highlight;
}

export default updateComments;
